package cn.bitkit.tools.common;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Optional;

import cn.bitkit.base.util.StringUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author changbo
 */
@Slf4j
public class CommonUtil {
	
	public static String getUserDir(){
		return System.getProperty("user.dir").replaceAll("\\\\", "/");
	}
	
	public static String getUserHome(){
		return System.getProperty("user.home").replaceAll("\\\\", "/");
	}

	/**
	 * 	获取局域网IP
	 * @return
	 */
	public static String getLanHostIp() {
		try {
			List<InetAddress> list = new ArrayList<>();
			Enumeration<NetworkInterface> netInterface = NetworkInterface.getNetworkInterfaces();
			netInterface.asIterator().forEachRemaining( networkInterface -> {
				Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
				addresses.asIterator().forEachRemaining(list::add);
			});
			Optional<InetAddress> optional = list.stream()
					.filter(e -> !e.isLoopbackAddress() && e.isSiteLocalAddress())
					.findFirst();
			if(optional.isPresent()){
				return optional.get().getHostAddress();
			}
			optional = list.stream()
					.filter(e -> !e.isLoopbackAddress())
					.findFirst();
			if(optional.isPresent()){
				return optional.get().getHostAddress();
			}
			return InetAddress.getLocalHost().getHostAddress();
		} catch (Exception e) {
			log.error("", e);
		}
		return null;
	}
	
    public static String getHostName() {
        InetAddress inetAddress;
        try {
            inetAddress = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            return "unkown";
        }
        String hostName = inetAddress.getHostName();
        if (null == hostName || hostName.isEmpty()) {
            hostName = inetAddress.getHostAddress();
        }
        if (null == hostName || hostName.isEmpty()) {
            hostName = inetAddress.getCanonicalHostName();
        }
        return hostName;
    }
	
	public static String getLocalMac(){
		//获取网卡，获取地址
		InetAddress ia;
		byte[] mac = null;
		try {
			ia = InetAddress.getLocalHost();
			mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
		} catch (Exception e) {
			log.error("", e);
			return null;
		}
		String hex = StringUtil.bytesToHexStr(mac);
		hex = hex.replaceAll(".{2}", "\\-$0");
		return hex.substring(1).toUpperCase();
	}
	
	public static String getMemoryInfo(){
		Runtime runtime = Runtime.getRuntime();
		long total = runtime.totalMemory()/1048576;
		long use = (runtime.totalMemory()-runtime.freeMemory())/1048576;
		return use + "M/" + total + "M";
	}
	
	public static int getThreadCount(){
		return ManagementFactory.getThreadMXBean().getThreadCount();
	}

	public static String getClassFile(Class<?> clazz){
		return "/"+clazz.getName().replaceAll("\\.", "/")+".java";
	}
	
}
